package com.example.m522;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "currency.db";
    private static final int DATABASE_VERSION = 1;

    // 汇率表
    private static final String TABLE_RATES = "exchange_rates";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_CURRENCY = "currency";
    private static final String COLUMN_RATE = "rate";
    private static final String COLUMN_TIMESTAMP = "timestamp";

    // 最后更新表
    private static final String TABLE_LAST_UPDATE = "last_update";
    private static final String COLUMN_LAST_UPDATE_DATE = "last_update_date";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建汇率表
        String createRatesTable = "CREATE TABLE " + TABLE_RATES + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_CURRENCY + " TEXT,"
                + COLUMN_RATE + " REAL,"
                + COLUMN_TIMESTAMP + " DATETIME DEFAULT CURRENT_TIMESTAMP)";
        db.execSQL(createRatesTable);

        // 创建最后更新时间表
        String createUpdateTable = "CREATE TABLE " + TABLE_LAST_UPDATE + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_LAST_UPDATE_DATE + " TEXT)";
        db.execSQL(createUpdateTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_RATES);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LAST_UPDATE);
        onCreate(db);
    }

    // 检查是否需要更新
    public boolean needsUpdate() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT " + COLUMN_LAST_UPDATE_DATE + " FROM " + TABLE_LAST_UPDATE + " ORDER BY " + COLUMN_ID + " DESC LIMIT 1", null);

        if (cursor != null && cursor.moveToFirst()) {
            String lastUpdate = cursor.getString(0);
            cursor.close();

            // 比较日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String today = sdf.format(new Date());

            return !today.equals(lastUpdate);
        }
        return true;
    }

    // 更新汇率数据
    public void updateRates(Map<String, Double> rates) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            // 清空旧数据
            db.delete(TABLE_RATES, null, null);

            // 插入新数据
            ContentValues values = new ContentValues();
            for (Map.Entry<String, Double> entry : rates.entrySet()) {
                values.put(COLUMN_CURRENCY, entry.getKey());
                values.put(COLUMN_RATE, entry.getValue());
                db.insert(TABLE_RATES, null, values);
            }

            // 更新最后更新时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String today = sdf.format(new Date());

            ContentValues updateValues = new ContentValues();
            updateValues.put(COLUMN_LAST_UPDATE_DATE, today);
            db.delete(TABLE_LAST_UPDATE, null, null);
            db.insert(TABLE_LAST_UPDATE, null, updateValues);

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    // 获取汇率
    public Map<String, Double> getRates() {
        Map<String, Double> rates = new HashMap<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_RATES, null, null, null, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range") String currency = cursor.getString(cursor.getColumnIndex(COLUMN_CURRENCY));
                @SuppressLint("Range") double rate = cursor.getDouble(cursor.getColumnIndex(COLUMN_RATE));
                rates.put(currency, rate);
            }
            cursor.close();
        }
        return rates;
    }
}